package org.onion.pattern.kit.common.jackson.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

public class LocalDateTime2TimestampSerializer extends JsonSerializer<LocalDateTime> {

    @Override
    public void serialize(LocalDateTime value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (value == null) {
            return;
        }

        ZoneId zoneId = ZoneId.systemDefault();
        // 或者使用UTC时区：ZoneId zoneId = ZoneId.of("UTC");
        Instant instant = value.atZone(zoneId).toInstant();

        jsonGenerator.writeNumber(instant.toEpochMilli());
    }

}
